package logic

import (
	"context"

	"book/common/errorx"
	"book/service/shorturl/cmd/api/internal/svc"
	"book/service/shorturl/cmd/api/internal/types"
	"book/service/shorturl/cmd/rpc/shorturl"

	"github.com/tal-tech/go-zero/core/logx"
)

type ShortenLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShortenLogic(ctx context.Context, svcCtx *svc.ServiceContext) ShortenLogic {
	return ShortenLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShortenLogic) Shorten(req types.ShortenReq) (resp interface{}, err error) {

	// 调用rpc服务
	res, err := l.svcCtx.ShorturlRpc.Shorten(l.ctx, &shorturl.ShortenReq{
		Url: req.Url,
	})
	if err != nil {
		return types.ShortenResp{}, err
	}

	return errorx.NewCodeSuccess(&types.ShortenResp{
		Shorten: res.Shorten,
	}, "success"), nil
}
